package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IAuditService auditService;

    @GetMapping("/audit/{id}")
    public ResponseResult audit(@PathVariable("id") Integer id) {
        auditService.audit(id);
        return ResponseResult.okResult();
    }

    @Autowired
    private IWmSensitiveService wmSensitiveService;

    /**
     * 从excel中读取敏感词更新到数据库
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadExcel")
    public ResponseResult uploadExcel(MultipartFile file) throws Exception {
        EasyExcel.read(file.getInputStream(), WmSensitive.class, new PageReadListener<WmSensitive>(dataList -> {
            for (WmSensitive wmSensitive : dataList) {
                //判断表中是否有这个敏感词
                LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmSensitive::getSensitives, wmSensitive.getSensitives());
                int count = wmSensitiveService.count(queryWrapper);
                if (count == 0) {
                    wmSensitive.setCreatedTime(new Date());
                    wmSensitiveService.save(wmSensitive);
                }
            }
        })).sheet().doRead();
        return ResponseResult.okResult("导入成功");
    }

    @PostMapping("/downloadExcel")
    public ResponseResult downloadExcel(HttpServletResponse response) throws Exception {
        List<WmSensitive> list = wmSensitiveService.list();
        //设置文件导出名  一个流：文件输出流 两个头：1.文件的打开方式（inline浏览器中直接打开，attachment附件下载） 2.文件的mine类型 text/html
        response.setHeader("content-disposition","attachment;filename=sensitive.xlsx");
        response.setContentType("text/html");
        EasyExcel.write(response.getOutputStream(),WmSensitive.class).sheet("敏感词").doWrite(list);
        return ResponseResult.okResult("导入成功");
    }


}